<?php

namespace App\Livewire;

use App\Models\Banner;
use App\Models\Book;
use App\Models\BorrowRecord;
use App\Models\Category;
use Illuminate\Database\Eloquent\Model;
use \Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Lazy;
use Livewire\Component;

#[Lazy(isolate: false)]
//#[Layout('components.layouts.app')]
class IndexPage extends Component
{
    public Collection $books;

    public int $page =1 ;

    public bool $loading = false;

    public bool $reachedEnd = false;
    public Collection $lastBook;

    public Collection $popularBook;

    public Collection $readOnlineBook;

    public Collection $borrowRecord;
    public Model $banner;

    public string $keyword = '';
    public function mount()
    {

        $this->lastBook = Book::query()->where('status', 1)->orderBy('updated_at', 'desc')->limit(10)->get();
        $this->banner = Banner::query()->where('name', 'index')->first();
        $this->popularBook = Book::query()->where('status', 1)->orderByDesc('weight')->limit(14)->get();
        $this->readOnlineBook = Book::query()->withCount('chapters')->whereHas('chapters')->where('status', 1)->orderByDesc('weight')->limit(14)->get();
        $this->borrowRecord = BorrowRecord::query()->with(['book:id,title,img','member:id,name'])->orderByDesc('id')->limit(10)->get();
        $list = $this->getPageData();
        if ($list->isNotEmpty()){
            $this->books = collect($list->items());
            $this->page++;
        }
    }

    public function search()
    {
        $this->redirect(route('search',['keyword' => $this->keyword]),navigate: true);
    }
    public function loadData(): void
    {
        $this->loading = true;
        $list = $this->getPageData();

        if ($list->isEmpty()) {
            $this->loading = false;
            $this->reachedEnd = true;
            return ;
        }
        $this->books = $this->books->concat($list->items());
        $this->loading = false;
        $this->page++;
    }

    public function getPageData(): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return Book::query()
            ->where('status', 1)
            ->orderBy('weight', 'desc')
            ->orderBy('updated_at', 'desc')
            ->paginate(8,['*'],'page',$this->page);
    }

    public function render()
    {
        return view('livewire.index-page')->layoutData([
            'category' => null,
        ]);
    }

}
